package com.swxy.filter;

import cn.hutool.json.JSONUtil;
import com.swxy.club.result.Result;
import com.swxy.club.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author 易
 */
@Component
@Slf4j
public class LoginGatewayFilter implements GatewayFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("token");

        if (token == null) {
//            log.warn("未找到 Token，请求被拦截: {}", request.getPath());
            return handleUnauthorized(exchange, "未登录，请先登录");
        }

        try {
            JWTUtil.verify(token);
            log.info("Token 验证通过: {}", request.getPath());
            return chain.filter(exchange);
        } catch (Exception e) {
            log.error("Token 验证失败", e);
            return handleUnauthorized(exchange, "Token 失效，请重新登录");
        }
    }

    private Mono<Void> handleUnauthorized(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        Result result = Result.error(HttpStatus.UNAUTHORIZED.value(), message);
        byte[] bytes = JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8);

        return response.writeWith(Mono.just(response.bufferFactory().wrap(bytes)));
    }

    // 设置拦截器的执行顺序（数值越小越先执行）
    @Override
    public int getOrder() {
        // 确保在 StripPrefix 之后执行
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}